package com.ctg.itrdc.k8sconsole.service.impl;

import io.fabric8.kubernetes.api.model.Pod;

import java.net.URL;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.constants.DockerConstant;
import com.ctg.itrdc.imageconsole.common.util.HttpRequestUtil;
import com.ctg.itrdc.imageconsole.data.dao.IClusterConfigDao;
import com.ctg.itrdc.imageconsole.data.entity.ClusterConfig;
import com.ctg.itrdc.imageconsole.service.ICommonService;
import com.ctg.itrdc.imageconsole.service.IK8sOperationRecordService;
import com.ctg.itrdc.imageconsole.util.KubeUtils;
import com.ctg.itrdc.k8sconsole.service.IRcService;
import com.ctg.itrdc.paspsdk.common.utils.file.PropertiesUtil;

/**
 * 
 * @description:
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年8月20日 上午10:39:57 Piao.Wu v1.0.0 create
 *
 */
@Component("rcService")
public class RcServiceImpl implements IRcService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private ExecutorService executorService = Executors.newFixedThreadPool(1);

	@Resource
	private ICommonService commonService;
	@Resource
	private IK8sOperationRecordService recordService;

	@Resource
	private IClusterConfigDao clusterConfigDao;

	@Override
	public String getRcs(String clusterCode, String perpage, String page, String name) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getRcs.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode);
		// 创建URL连接
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.queryParam("perpage", perpage).queryParam("page", page).queryParam("name", name).request().get();

		return requestUtil.getResponseJsonData(response);
	}
	
	
	@Override
	public String getRcsByNamesp(String clusterCode, String namesp, String name, String perpage, String page) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getRcsByNamesp.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, namesp);
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.queryParam("perpage", perpage).queryParam("page", page).queryParam("name", name).request().get();

		return requestUtil.getResponseJsonData(response);
	}
	

	@Override
	public String getRcDetail(String clusterCode, String name, String namesp) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getRcDetail.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, namesp, name);
		// 创建URL连接
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.request().get();

		return requestUtil.getResponseJsonData(response);
	}

	@Override
	public String updateRcReplicas(String clusterCode, String name, String namesp, Integer replicas) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("replicas", replicas);

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "updateRcReplicas.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, namesp, name);
		// 创建URL连接
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.request().post(Entity.entity(paraMap, MediaType.APPLICATION_JSON_TYPE));

		return requestUtil.getResponseJsonData(response);
	}
	
	@Override
	public String delRc(String clusterCode, String namesp, String name) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "delRc.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, namesp, name);
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.request().delete();

		return requestUtil.getResponseJsonData(response);
	}

	@Override
	public Long restartRc(final String k8sUrl, final String namesp, final String rcName) {
		List<Pod> pods = KubeUtils.queryPodsByRcName(k8sUrl, rcName);
		if (pods == null) {
			logger.warn("k8sUrl={},rcName={},在重启时没有查出pod！", k8sUrl, rcName);
			return null;
		}
		try {
			final Integer currentPodNum = pods.size();
			final Long recordId = recordService.saveRecord(k8sUrl, "default", rcName, currentPodNum,
					DockerConstant.K8sOperationRecord.OPERATION_OBJECT_RC,
					DockerConstant.K8sOperationRecord.OPERATION_TYPE_RC_RESTART);
			executorService.submit(new Runnable() {
				@Override
				public void run() {
					boolean isSuccess = false;
					// 重启rc的方式：将实例数缩容至0 再扩容至原来的实例数
					isSuccess = KubeUtils.updateRcReplicas(k8sUrl, "default", rcName, 0);
					if (isSuccess) {
						while (true) {
							List<Pod> podsByNarrow = KubeUtils.queryPodsByRcName(k8sUrl, rcName);
							if (podsByNarrow == null || podsByNarrow.size() == 0) {
								break;
							}
						}
						// 只有缩容至0成功后，才进行扩容至原来的实例数
						if (!KubeUtils.updateRcReplicas(k8sUrl, "default", rcName, currentPodNum)) {
							recordService.updateRecordStatus(recordId, DockerConstant.K8sOperationRecord.EXECUTE_FAIL);
						}
					} else {
						recordService.updateRecordStatus(recordId, DockerConstant.K8sOperationRecord.EXECUTE_FAIL);
					}
				}
			});
			return recordId;
		} catch (Exception e) {
			logger.error("重启失败", e);
			return null;
		}
	}

	@Override
	public Long deleteRc(String k8sUrl, String namesp, String rcName) {
		Long recordId = recordService.saveRecord(k8sUrl, "default", rcName, null,
				DockerConstant.K8sOperationRecord.OPERATION_OBJECT_RC,
				DockerConstant.K8sOperationRecord.OPERATION_TYPE_RC_DELETE);
		if (!KubeUtils.deleteRcAndPod(k8sUrl, rcName)) {
			recordService.updateRecordStatus(recordId, DockerConstant.K8sOperationRecord.EXECUTE_FAIL);
		}
		return recordId;
	}

	@Override
	public Long expandOrNarrowRc(String k8sUrl, String namesp, String rcName, Integer replicas) {
		Long recordId = recordService.saveRecord(k8sUrl, "default", rcName, replicas,
				DockerConstant.K8sOperationRecord.OPERATION_OBJECT_RC,
				DockerConstant.K8sOperationRecord.OPERATION_TYPE_RC_SCALE);
		if (!KubeUtils.updateRcReplicas(k8sUrl, "default", rcName, replicas)) {
			recordService.updateRecordStatus(recordId, DockerConstant.K8sOperationRecord.EXECUTE_FAIL);
		}
		return recordId;
	}

}
